package com.hw.hcit.feature;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JTestItem;

public class BatteryLevelTestItem extends JTestItem{
	private String TAG = "BatteryLevelTestItem";
    TextView mTestResult;
    private boolean batteryLevelSuccess = false;
    private Button mButton1,mButton2;
    private String batresult;
    private String mPercent,mVoltage,mTemperature;
    private Context mContext;
    
    private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case 0:
				mButton1.setEnabled(true);
				break;
			case 1:
				mButton2.setEnabled(true);
				break;
				
			default:
				break;
			}
		}
	};
    
    public BatteryLevelTestItem() {
        super();
    }

   @Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = Config.GetActivity().getApplicationContext();
		mPercent = mContext.getString(R.string.battery_percent);
		mVoltage = mContext.getString(R.string.battery_voltage);
		mTemperature = mContext.getString(R.string.battery_temp);
	}
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
 {
		View rootView = inflater.inflate(R.layout.batterylevel_test, container,
				false);
		mTestResult = (TextView) rootView.findViewById(R.id.test_result);
		mButton1 = (Button) rootView.findViewById(R.id.button1);
		mButton2 = (Button) rootView.findViewById(R.id.button2);
		mButton1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (Config.CURR_PROJECT.isAuto()) {
					Log.d(TAG, "Config.ageingTested" + Config.ageingTested);
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(0, 'P');

					} else {
						rewriteOneByteOfNv2499(31, 'P');
					}
				}
				 testFinish(true, 1, true);
				
			}
		});
		mButton2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showBatteryTooLow();
				if (Config.CURR_PROJECT.isAuto()) {
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(0, 'F');

					} else {
						rewriteOneByteOfNv2499(31, 'F');
					}
				}
				
/*				testFinish(false, 1, false);*/
				Config.STEP = Config.UI_PROJECTS;
				Config.GetActivity().getFragmentManager().beginTransaction()
						.replace(R.id.frame_layout, Config.PROJECTS.getUI()).commit();
			}
		});

		
		return rootView;
	}

    @Override
    public boolean getResult() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public String getResultInfo() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void startTest() {
        // TODO Auto-generated method stub
    // start to test
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = Config.GetActivity().getApplicationContext()
                .registerReceiver(null, ifilter);
        // 当前剩余电量
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        // 电量最大值
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        //电池电压
        double voltage = (double)batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)/1000;
      //电池温度
        float temperature = Float.valueOf((batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)))/10;
        // 电量百分比
        Log.d(TAG, "vol--->"+batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)+"\n"+
                  "tem--->"+batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
        float batteryPct = level / (float) scale;
        // if(mTestResult!=null)
        {
            if (batteryPct >= 0.2 && 3.45<=voltage && voltage <= 4.4 && 10 <=temperature && temperature <= 40 ) {
                Log.d(TAG, "batteryLevelSuccess----->true");
                batteryLevelSuccess = true;
                mTestResult.setText(R.string.test_success);
                mTestResult.setTextColor(Color.GREEN);
                mHandler.sendEmptyMessage(0);
            } else {
            	StringBuilder stringBuilder = new StringBuilder();
            	if(batteryPct < 0.2){
            		stringBuilder.append(mPercent).append(batteryPct).append("\n");
            	}
            	
            	if(voltage <3.45 || voltage > 4.4){
            		stringBuilder.append(mVoltage).append(voltage).append("V").append("\n");
            	}
            	
            	if(temperature < 10 || temperature > 40){
            		stringBuilder.append(mTemperature).append(temperature).append("℃");
            	}
                Log.d(TAG, "batteryLevelfalse----->"+stringBuilder.toString());
                batteryLevelSuccess = false;
                batresult = stringBuilder.toString();
                mTestResult.setText(batresult);
                mTestResult.setTextColor(Color.RED);
                mHandler.sendEmptyMessage(1);
            }
            mTestResult.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void stopTest() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void refresh()
    {
        
    }

    
    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mButton1.setEnabled(false);
        mButton2.setEnabled(false);
        startTest();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        return true;
    }


}
